"""
cron: 00 06 * * *
new Env('京东附近抽奖');
"""

import requests
import json
import time
import os
import re
import sys
import random
import string
import urllib
from urllib.parse import quote
import logging

logging.basicConfig(level=logging.INFO, format='%(message)s')
logger = logging.getLogger(__name__)

# 获取cookie
def get_cookie():
    url='http://127.0.0.1:5700/api/envs'
    try:
        filePath = '/ql/data/config/auth.json';
        if os.path.exists(filePath) == False:
            filePath = '/ql/config/auth.json';
        with open(filePath, 'r') as f:
            token=json.loads(f.read())['token']
        headers={
            'Accept':'application/json',
            'authorization':'Bearer '+token,
            }
        response=requests.get(url=url,headers=headers)
        data = json.loads(response.text)['data'];
        cookies = [];
        for i in range(len(data)):
            if data[i]['name']=='JD_COOKIE' and data[i]['status'] == 0:
                cookie = data[i]['value'];
                cookies = cookies + cookie.split('&');

        return cookies;
    except:
        logger.info('读取auth.json文件出错，跳过获取备注')
    return '';

# 获取header
def get_header(cookie):
    headers = {
      'Host': 'api.m.jd.com',
      'Accept': 'application/json, text/plain, */*',
      'Content-Type': 'application/x-www-form-urlencoded',
      'Origin': 'https://pro.m.jd.com',
      'Accept-Language': 'zh-cn',
      'User-Agent': "jdapp;iPhone;9.4.4;14.3;network/4g;Mozilla/5.0 (iPhone; CPU iPhone OS 14_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148;supportJDSHWK/1",
      'Referer': 'https://pro.m.jd.com',
      'Accept-Encoding': 'gzip, deflate, br',
      'Cookie': cookie
    }
    return headers;

# 获取任务列表
def get_task(cookie):
    url = 'https://api.m.jd.com/client.action?functionId=queryInteractiveInfo';
    headers = get_header(cookie);
    data = 'appid=babelh5&body={"sourceCode":"aceaceqingzhan","encryptProjectId":"3pTog2pHcLYLDqBasKmrERcM8Efw","ext":{"rewardEncryptAssignmentId":"2AYp1JK4pKGbaqdYg8vxwDCMXGmS","needNum":50}}&sign=11&t=' + getTime();
    response=requests.post(url=url,headers=headers,data=data)
    data = json.loads(response.text);
    dataList = data['assignmentList'];
    for item in dataList:
        if item['completionFlag'] == True:
            logger.info(item['assignmentName'] + ' 任务已完成');
            continue;
        else:
            keys = item['ext'].keys();
            if "shoppingActivity" in keys:
                itemId = item['ext']['shoppingActivity'][0]['itemId']
                taskId = item['encryptAssignmentId'];
                logger.info('开始完成任务---' + item['assignmentName'] + ' 任务ID：' + item['encryptAssignmentId'] + ' itemId：' + itemId);
                done_taks(taskId , itemId , cookie);

# 完成任务
def done_taks(taskId , itemId , cookie):
    url = 'https://api.m.jd.com/client.action?functionId=doInteractiveAssignment';
    headers = get_header(cookie);
    data = 'appid=babelh5&body={"sourceCode":"aceaceqingzhan","encryptProjectId":"3pTog2pHcLYLDqBasKmrERcM8Efw","encryptAssignmentId":"' + taskId + '","itemId":"' + itemId + '"}&sign=11&t=' + getTime();
    response=requests.post(url=url,headers=headers,data=data)
    data = json.loads(response.text);
    if data['msg'] == '任务完成':
        logger.info(data['msg'])
    else:
        logger.info(data)
    time.sleep(1);

# 开始抽奖
def dec_integral(cookie):
    url = 'https://api.m.jd.com/client.action?functionId=doInteractiveAssignment';
    data = 'appid=babelh5&body={"sourceCode":"aceaceqingzhan","encryptProjectId":"3pTog2pHcLYLDqBasKmrERcM8Efw","encryptAssignmentId":"2AYp1JK4pKGbaqdYg8vxwDCMXGmS","completionFlag":true,"ext":{"exchangeNum":1}}&sign=11&t=' + getTime();
    headers = get_header(cookie);
    logger.info('开始抽奖')
    response=requests.post(url=url,headers=headers,data=data)
    data = json.loads(response.text);
    if data['msg'] != 'success':
        logger.info('抽奖失败-' + data['msg'])
        return;
    dataList = data['rewardsInfo']
    try:

        success = dataList['successRewards'];
        failed = dataList['failRewards'];
        if not bool(success):
            logger.info('抽奖成功：' + failed[0]['msg']);
        else:
            logger.info(success);
            logger.info('抽奖成功：');
    except:
        logger.info(dataList)
    time.sleep(2);

# 获取当前积分
def get_currentIntegral(cookie):
    url = 'https://api.m.jd.com/client.action?functionId=queryInteractiveRewardInfo';
    data = 'appid=babelh5&body={"sourceCode":"aceaceqingzhan","encryptProjectId":"3pTog2pHcLYLDqBasKmrERcM8Efw","ext":{"detailEncryptAssignmentIds":[],"needExchangeRestScore":1,"detailTypeFlag":"1"}}&sign=11&t=' + getTime();
    headers = get_header(cookie);
    response=requests.post(url=url,headers=headers,data=data)
    data = json.loads(response.text);
    dataList = data['exchangeRestScoreMap'];
    value = list(dataList.values());
    logger.info('当前有' + str(value[0]) + '个积分');
    return value[0];

# 获取时间戳
def getTime():
    return str(int(time.time() * 1000));

def run():
    # 读取多cookie
    cookies = get_cookie()
    for cookie in cookies:
        startIndex = cookie.rindex('pt_pin');
        userName = cookie[startIndex:len(cookie)].replace('pt_pin=' , '');
        logger.info('===========京东账号' + userName + '=========')
        get_task(cookie);
        integral = get_currentIntegral(cookie);
        startIntegral = 200;
        if integral < startIntegral:
            logger.info('最小' + str(startIntegral) + '个积分起抽');
        else:
            num = int(integral / startIntegral)
            for x in range(num):
                dec_integral(cookie);

        logger.info("\r\n\r\n")
        time.sleep(1);

if __name__ == '__main__':
    run()